from app import app
from flask import Flask, request, jsonify, send_from_directory
import sys
import os
import uuid
import time
import random
import cv2
import numpy as np
from rknnlite.api import RKNNLite
sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
from model.model_process import simulate_image_recognition

# 配置
UPLOAD_FOLDER = 'uploads'
MAX_CONTENT_LENGTH = 10 * 1024 * 1024  # 10MB

OUTPUT_DIR = "app/uploads"

# 创建上传目录
os.makedirs(UPLOAD_FOLDER, exist_ok=True)

app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['MAX_CONTENT_LENGTH'] = MAX_CONTENT_LENGTH

# 允许的图片扩展名
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif', 'webp'}

def allowed_file(filename):
    """检查文件扩展名是否允许"""
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

@app.route('/api/recognize', methods=['POST'])
def recognize():
    """处理图片识别请求"""
    # 检查是否有文件部分
    if 'image' not in request.files:
        return jsonify({"error": "没有图片文件"}), 400
    
    file = request.files['image']
    
    # 如果用户没有选择文件
    if file.filename == '':
        return jsonify({"error": "没有选择图片"}), 400
    
    # 检查文件是否合法
    if file and allowed_file(file.filename):
        # 生成唯一文件名
        filename = f"{uuid.uuid4()}.{file.filename.rsplit('.', 1)[1].lower()}"
        filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
        
        # 保存文件
        file.save(filepath)
        
        # 进行图片识别（模拟）
        annotations = simulate_image_recognition(filepath, OUTPUT_DIR)
        
        # 返回结果
        return jsonify({
            "success": True,
            "image_url": f"/uploads/{filename}",
            "annotations": annotations
        })
    
    return jsonify({"error": "不支持的文件类型"}), 400

@app.route('/uploads/<filename>')
def uploaded_file(filename):
    """提供上传文件的访问"""
    return send_from_directory(app.config['UPLOAD_FOLDER'], filename)

@app.route('/')
def index():
    """返回前端页面"""
    return send_from_directory('./static', 'index.html')

if __name__ == '__main__':
    app.run(debug=True)
